package file

import (
	"io/ioutil"
	"os"
	"path/filepath"
)

func MkDir(path string) {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		os.MkdirAll(path, os.ModePerm)
	}
}

func RemoveFile(path string) {
	if _, err := os.Stat(path); os.IsExist(err) {
		os.Remove(path)
	}
}

func WriteFile(filePath string, fileBytes []byte) error {

	// 写文件
	newFile, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer newFile.Close()

	if _, err := newFile.Write(fileBytes); err != nil || newFile.Close() != nil {
		return err
	}

	return nil
}

func GetFileName(dir string) ([]string, error) {
	var result []string
	if _, err := os.Stat(dir); os.IsExist(err) {
		return nil, err
	}

	files, _ := ioutil.ReadDir(dir)
	for _, f := range files {

		result = append(result, f.Name())
	}
	return result, nil
}

func Exists(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

func GetFileFullPath(dir string) ([]string, error) {
	if _, err := os.Stat(dir); os.IsExist(err) {
		return nil, err
	}

	filepathNames, err := filepath.Glob(filepath.Join(dir, "*"))
	if err != nil {
		return nil, err
	}

	return filepathNames, nil
}
func ReadFile(name string) string {
	content, err := ioutil.ReadFile(name)
	if err != nil {

		os.Exit(1)
	}
	return string(content)
}

func CombineFile(dir, filename string) string {
	return filepath.Join(dir,filename)
}
